﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Auth.Interfaces;
using System.Web.Security;
using Auth.Implementations;

namespace Auth.SessionContext
{
    public static class Current
    {
        public static IUser User
        {
            get
            {
                var user = HttpContext.Current.Session["CurrentUser"] as IUser;

                if (user == null) {
                    HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (authCookie == null || authCookie.Value == "")
                        return null;

                    FormsAuthenticationTicket authTicket;
                    try
                    {
                        authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                        Auth.SessionContext.Current.User = new User
                        {
                            Username = authTicket.UserData,
                            Roles = new List<UserRole>
						{
							UserRole.Administrator
						}
                        };
                    }
                    catch
                    {
                        return null;
                    }
                }

                return user;
            }
            set
            {
                HttpContext.Current.Session["CurrentUser"] = value;
            }
        }
    }
}
